<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2 class="title">AI学习辅助平台</h2>
        <p class="subtitle">让AI助力您的学习之旅</p>
      </div>

      <div class="form-container">
        <div class="form-tabs">
          <div :class="['tab-item', activeTab === 'login' ? 'active' : '']" @click="activeTab = 'login'">
            登录
          </div>
          <div :class="['tab-item', activeTab === 'register' ? 'active' : '']" @click="activeTab = 'register'">
            注册
          </div>
          <div class="tab-slider" :style="tabSliderStyle"></div>
        </div>

        <!-- 登录表单 -->
        <div v-show="activeTab === 'login'" class="form-box">
          <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules">
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" placeholder="用户名" prefix-icon="User" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="loginForm.password" type="password" placeholder="密码" prefix-icon="Lock" show-password
                @keyup.enter="handleLogin" />
            </el-form-item>
            <el-form-item v-if="captchaEnabled" prop="code">
              <div class="captcha-container">
                <el-input v-model="loginForm.code" placeholder="验证码" prefix-icon="Key" @keyup.enter="handleLogin" />
                <img class="captcha-img" :src="captchaImg" @click="getCaptchaImage" alt="验证码" />
              </div>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
              <a class="forget-link">忘记密码？</a>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="submit-btn" :loading="loading" @click="handleLogin">登录</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 注册表单 -->
        <div v-show="activeTab === 'register'" class="form-box">
          <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules">
            <el-form-item prop="username">
              <el-input v-model="registerForm.username" placeholder="用户名" prefix-icon="User" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="registerForm.password" type="password" placeholder="密码" prefix-icon="Lock"
                show-password />
            </el-form-item>
            <el-form-item prop="confirmPassword">
              <el-input v-model="registerForm.confirmPassword" type="password" placeholder="确认密码" prefix-icon="Lock"
                show-password />
            </el-form-item>
            <el-form-item prop="email">
              <el-input v-model="registerForm.email" placeholder="邮箱" prefix-icon="Message" />
            </el-form-item>
            <el-form-item v-if="captchaEnabled" prop="code">
              <div class="captcha-container">
                <el-input v-model="registerForm.code" placeholder="验证码" prefix-icon="Key"
                  @keyup.enter="handleRegister" />
                <img class="captcha-img" :src="captchaImg" @click="getCaptchaImage" alt="验证码" />
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="submit-btn" :loading="loading" @click="handleRegister">注册</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>

    <!-- 背景动画 -->
    <div class="background-animation">
      <div v-for="n in 10" :key="n" class="circle"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { login, register, getCaptcha } from '@/api/login';
import { setToken, getToken } from "@/utils/auth";

const router = useRouter();
const route = useRoute();
const activeTab = ref('login');
const loading = ref(false);
const captchaEnabled = ref(true);
const captchaImg = ref('');
const uuid = ref('');
const loginFormRef = ref(null);
const registerFormRef = ref(null);

// 登录表单
const loginForm = reactive({
  username: '',
  password: '',
  code: '',
  uuid: '',
  rememberMe: false
});

// 注册表单
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  code: ''
});

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
};

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名长度不能少于3个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
};

// 计算tab滑块的样式
const tabSliderStyle = computed(() => {
  return {
    transform: activeTab.value === 'login' ? 'translateX(0)' : 'translateX(100%)'
  };
});

// 获取验证码
const getCaptchaImage = async () => {
  try {
    const res = await getCaptcha();
    captchaImg.value = 'data:image/gif;base64,' + res.img;
    uuid.value = res.uuid;
    loginForm.uuid = res.uuid;
    registerForm.uuid = res.uuid;
  } catch (error) {
    console.error('获取验证码出错:', error);
    ElMessage.error('获取验证码失败');
  }
};

// 登录处理
const handleLogin = () => {
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        const res = await login(
          loginForm.username,
          loginForm.password,
          loginForm.code,
          uuid.value
        );

        // 存储token
        // localStorage.setItem('token', res.data.access_token);
        setToken(res.data.access_token);
        console.log('登录成功:', res.data.access_token);
        ElMessage.success('登录成功');

        // 跳转到首页或重定向页面
        const redirect = route.query.redirect || '/';
        router.push(redirect);
      } catch (error) {
        console.error('登录出错:', error);
        ElMessage.error(error.message || '登录失败，请稍后再试');
        // 刷新验证码
        if (captchaEnabled.value) {
          getCaptchaImage();
        }
      } finally {
        loading.value = false;
      }
    }
  });
};

// 注册处理
const handleRegister = () => {
  registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        await register({
          username: registerForm.username,
          password: registerForm.password,
          email: registerForm.email,
          code: registerForm.code,
          uuid: uuid.value
        });

        ElMessage.success('注册成功，请登录');
        // 切换到登录页
        activeTab.value = 'login';
        // 清空注册表单
        registerFormRef.value.resetFields();
        // 刷新验证码
        if (captchaEnabled.value) {
          getCaptchaImage();
        }
      } catch (error) {
        console.error('注册出错:', error);
        ElMessage.error(error.message || '注册失败，请稍后再试');
        // 刷新验证码
        if (captchaEnabled.value) {
          getCaptchaImage();
        }
      } finally {
        loading.value = false;
      }
    }
  });
};

// 组件挂载时获取验证码
onMounted(() => {
  // 检查是否已登录，如果已登录则跳转到首页
  const token = getToken();
  if (token) {
    router.push('/');
    return;
  }
  
  if (captchaEnabled.value) {
    getCaptchaImage();
  }

  // 随机生成背景动画的圆圈位置和大小
  const circles = document.querySelectorAll('.circle');
  circles.forEach(circle => {
    const size = Math.random() * 100 + 50;
    const x = Math.random() * 100;
    const y = Math.random() * 100;
    const delay = Math.random() * 5;
    const duration = Math.random() * 10 + 10;

    circle.style.width = `${size}px`;
    circle.style.height = `${size}px`;
    circle.style.left = `${x}%`;
    circle.style.top = `${y}%`;
    circle.style.animationDelay = `${delay}s`;
    circle.style.animationDuration = `${duration}s`;
  });
});
</script>

<style lang="scss" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
  width: 100%;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.login-box {
  width: 420px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  padding: 30px;
  z-index: 10;
  animation: fadeIn 0.5s ease-in-out;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;

  .title {
    font-size: 28px;
    color: #333;
    margin-bottom: 10px;
    font-weight: 600;
  }

  .subtitle {
    font-size: 16px;
    color: #666;
  }
}

.form-container {
  .form-tabs {
    display: flex;
    position: relative;
    margin-bottom: 25px;
    border-bottom: 1px solid #eee;

    .tab-item {
      flex: 1;
      text-align: center;
      padding: 12px 0;
      font-size: 16px;
      color: #666;
      cursor: pointer;
      transition: all 0.3s;

      &.active {
        color: #409eff;
        font-weight: 500;
      }

      &:hover {
        color: #409eff;
      }
    }

    .tab-slider {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 50%;
      height: 2px;
      background-color: #409eff;
      transition: transform 0.3s ease;
    }
  }

  .form-box {
    animation: fadeIn 0.3s ease-in-out;
  }
}

.captcha-container {
  display: flex;
  align-items: center;

  .el-input {
    flex: 1;
  }

  .captcha-img {
    margin-left: 10px;
    height: 38px;
    cursor: pointer;
    border-radius: 4px;
  }
}

.forget-link {
  float: right;
  font-size: 14px;
  color: #409eff;
  cursor: pointer;

  &:hover {
    text-decoration: underline;
  }
}

.submit-btn {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
}

// 背景动画
.background-animation {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;

  .circle {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    animation: float 15s infinite linear;
  }
}

@keyframes float {
  0% {
    transform: translateY(0) rotate(0deg);
    opacity: 0.8;
  }

  100% {
    transform: translateY(-1000px) rotate(720deg);
    opacity: 0;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式调整
@media (max-width: 480px) {
  .login-box {
    width: 90%;
    padding: 20px;
  }
}
</style>